import {onUnmounted} from "vue";

export function useMouseDrag() {

    let isResizing = false;
    let startX, startWidth;
    let _resizeHandle = null, _leftDOM = null, _rightDOM = null;
    let _type = '';

    /**
     * 鼠标按下
     * @param event
     */
    const resizeHandleMousedown = (event) =>{
        isResizing = true;
        startX = event.clientX;
        startWidth = parseFloat(getComputedStyle(_leftDOM).width);
    }

    /**
     * 鼠标移动
     * @param event
     */
    const resizeHandleMousemove = (event) =>{
        if (!isResizing) return;

        const deltaX = event.clientX - startX;
        const newWidth = Math.max(0, startWidth + deltaX);

        if(newWidth > 210) {
            _leftDOM.style.width = `${newWidth}px`;
            _rightDOM.style.width = `calc(100% - ${newWidth}px)`;

            // 记录左右两边宽度
            if (sessionStorage.getItem('dragWidth')) {
                let dragObj = JSON.parse(sessionStorage.getItem('dragWidth'));
                dragObj[_type] = { right: _rightDOM.style.width, left: _leftDOM.style.width }
                sessionStorage.setItem('dragWidth', JSON.stringify(dragObj));
            } else {
                sessionStorage.setItem('dragWidth', JSON.stringify({ [_type] : { right: _rightDOM.style.width, left: _leftDOM.style.width } }));
            }
        }
    }

    /**
     * 鼠标抬起
     * @param event
     */
    const resizeHandleMouseup = (event) =>{
        isResizing = false;
    }


    /**
     * 拖拽
     * @param resizeHandle
     * @param leftDOM
     * @param rightDOM
     * @param type
     */
    const dragDest = (resizeHandle, leftDOM, rightDOM, type) =>{
        _resizeHandle = resizeHandle;
        _leftDOM = leftDOM;
        _rightDOM = rightDOM;
        _type = type;

        // 开始拖动手柄
        _resizeHandle.addEventListener('mousedown', resizeHandleMousedown);

        // 监听全局 mousemove 事件以处理拖动
        document.addEventListener('mousemove', resizeHandleMousemove);

        // 停止拖动手柄
        document.addEventListener('mouseup', resizeHandleMouseup);
    }

    /**
     * 卸载时
     */
    onUnmounted(() =>{
        _resizeHandle.removeEventListener('mousedown', resizeHandleMousedown);
        document.removeEventListener('mousemove', resizeHandleMousemove);
        document.removeEventListener('mouseup', resizeHandleMouseup);
    })

    return {
        dragDest
    }
}
